﻿using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;

namespace ListenerService
{
    using System.Collections.Generic;
    using Properties;

    public partial class MyService : ServiceBase
    {
        //定时器
        private System.Timers.Timer timer = new System.Timers.Timer() { Interval = 5000, AutoReset = true };

        private string format = "hh:mm:ss.fff";

        private UsbDriverWatcher watcher = new UsbDriverWatcher();

        public MyService()
        {
            InitializeComponent();

            //启用暂停恢复
            //base.CanPauseAndContinue = true;

            //到达时间的时候执行事件
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Trace.TraceInformation(DateTime.Now.ToString(format) + " 心跳");
        }

        //启动服务执行
        protected override void OnStart(string[] args)
        {
            //是否执行System.Timers.Timer.Elapsed事件；
            Trace.TraceInformation(DateTime.Now.ToString(format) + " 启动");
            timer.Enabled = true;
            watcher.OnDeviceChanged += Watcher_OnDeviceChanged;
            watcher.Start();
        }

        private void Watcher_OnDeviceChanged(object sender, DeviceChangedEventArgs e)
        {
            Trace.TraceInformation($"{e.Action},{e.Description},{e.DriverName},Size {e.Size},FreeSpace {e.FreeSpace}");
            if (e.Action == DeviceChangedAction.Add)
            {
                foreach (var item in GetFiles(e.FullPath))
                    Trace.TraceInformation(item);
                Trace.TraceInformation("--------------------------------");
                GetFiles(e.FullPath, file =>
                {
                    string disDir = Settings.Default.Path; // 目标文件夹
                    string filePath = file.Replace(e.FullPath, disDir); // 目标文件路径
                    String fileDir = Path.GetDirectoryName(filePath); // 目标文件所在文件夹
                    if (!Directory.Exists(fileDir))
                        Directory.CreateDirectory(fileDir);
                    File.Copy(file, filePath, true);
                    Trace.TraceInformation($"copy {file} success!");
                });
            }
        }

        public string[] GetFiles(string dir, Action<string> action = null)
        {
            if (!Directory.Exists(dir)) throw new ArgumentException();

            List<string> files = new List<string>();
            foreach (var item in Directory.GetDirectories(dir))
            {
                if (!item.Contains("System Volume Information"))
                    files.AddRange(GetFiles(item, action));
            }
            foreach (var item in Directory.GetFiles(dir))
            {
                files.Add(item);
                action?.Invoke(item);
            }
            return files.ToArray();
        }

        //停止服务执行
        protected override void OnStop()
        {
            watcher.Stop();
            watcher.OnDeviceChanged -= Watcher_OnDeviceChanged;
            Trace.TraceInformation(DateTime.Now.ToString(format) + " 停止");
        }

        //恢复服务执行
        protected override void OnContinue()
        {
            Trace.TraceInformation(DateTime.Now.ToString(format) + " 继续");
            timer.Start();
        }

        //暂停服务执行
        protected override void OnPause()
        {
            Trace.TraceInformation(DateTime.Now.ToString(format) + " 暂停");
            timer.Stop();
        }
    }
}